#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<string.h>
#include<unistd.h>
#include<arpa/inet.h>

#define SERVER_PORT 8888
#define BUFF_LINE 1024

void 
handle_udp_msg(int fd)
{
	char buf[BUFF_LINE];
	socklen_t len;

	int count;
	struct sockaddr_in client_addr;

	while(1)
	{
		memset(buf, 0, BUFF_LINE);
		len = sizeof(client_addr);
		count = recvfrom( fd, buf, BUFF_LINE, 0, (struct sockaddr*)&client_addr, &len); //it's a congestion function
		if(count == -1)
		{
			printf("receive data fail!\n");
			return ;	
		}	
		printf("client:%s\n", buf);
		memset(buf, 0, BUFF_LINE);
		sprintf(buf, "I have received %d bytes data!\n", count);
		printf("server:%s\n", buf);
		sendto(fd, buf, BUFF_LINE, 0, (struct sockaddr*)&client_addr, len);
	}
}

/*
	server:
		socket -> bind -> recvfrom -> sendto -> close
*/
int main(int argc, char **argv)
{
	int server_fd, ret;
	struct sockaddr_in ser_addr;

	server_fd = socket(AF_INET, SOCK_DGRAM, 0);
	if(server_fd<0)
	{
		printf("create socket fail!");
		return -1;
	}
	memset(&ser_addr, 0, sizeof(ser_addr));
	ser_addr.sin_family = AF_INET;
	ser_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	ser_addr.sin_port = htons(SERVER_PORT);

	ret = bind(server_fd, (struct sockaddr*)&ser_addr, sizeof(ser_addr));
	if( ret < 0 )
	{
		printf("socket bind failed!");
		return -1;	
	}

	handle_udp_msg(server_fd);

	close(server_fd);
	return 0;
}
